import React from 'react';
import {Button, Image, Input, Popconfirm, Table, Tag, Typography} from 'antd';
import moment from 'moment';
import style from './index.less'
import {SearchOutlined} from "@ant-design/icons";
import Highlighter from "react-highlight-words";
import EditUserModal from "./editUserModal";

export default class UserTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userTable: {},
      loading: false,
      modalVisible: false,
    }
    this.columns = [
      {
        title: '#',
        dataIndex: 'key',
        key: 'key',
        width: 55,
        render: text => <span>{text + 1}</span>,
      },
      {
        title: '用户名',
        dataIndex: 'username',
        key: 'username',
        width: 200,
      },
      {
        title: '密码',
        dataIndex: 'password',
        key: 'password',
        width: 200,
      },
      {
        title: '用户角色',
        dataIndex: 'user_role',
        key: 'user_role',
        width: 200,
      },
      {
        title: '最近登陆',
        dataIndex: 'last_login',
        key: 'last_login',
        width: 300,
        render: text => moment(text).format('YYYY-MM-DD HH:mm:ss'),
        sorter: (a, b) => a.last_login - b.last_login,
        sortDirections: ['descend', 'ascend'],
      },
      {
        title: '用户余额',
        dataIndex: 'balance',
        key: 'balance',
        width: 120,
      },
      {
        title: '操作',
        key: 'action',
        width: 150,
        render: (record) => <div>
          <Popconfirm title={`你确定要删除这个用户吗？`}
                      onConfirm={this.onDelete.bind(this, record)}
                      okText="确定"
                      okButtonProps={{ danger: true }}
                      cancelText="取消"
                      placement="rightBottom"
          >
            <Button type='link' style={{color: 'red'}}>删除</Button>
          </Popconfirm>
          <Button onClick={this.onActionBtnClick.bind(this, record)} type='link' style={{color: 'blue'}}>修改</Button>
        </div>
      },
    ];
    this.state = {
      dataLoading: false,
      tableWidth: 'max-content',
    };
  }


  // handler
  onDelete = async record => {
    await this.setState({ dataLoading: true });
    await this.props.dispatch({type: 'adminModel/deleteUserByUsername', payload: {username: record.username}});
    await this.setState({ dataLoading: false });
  };

  showModal = () => {
    this.setState({modalVisible: true});
  };

  onActionBtnClick = async record => {
    await this.setState({userTable: record});
    await this.showModal();
  };

  hideModal = () => {
    this.setState({modalVisible: false});
  };


  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
        <div style={{ padding: 8 }}>
          <Input
              ref={node => {
                this.searchInput = node;
              }}
              placeholder={`搜索 ${dataIndex}`}
              value={selectedKeys[0]}
              onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
              onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
              style={{ width: 188, marginBottom: 8, display: 'block' }}
          />
          <Button
              type="primary"
              onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
              icon={<SearchOutlined/>}
              size="small"
              style={{ width: 90, marginRight: 8 }}
          >
            确定
          </Button>
          <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
            清空键入
          </Button>
        </div>
    ),
    // 配置表格上filter按钮的样式
    filterIcon: filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }}/>,
    // 配置搜索规则，value传入
    onFilter: (value, record) =>
        record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase()),

    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },

    render: text =>
        this.state.searchedColumn === dataIndex ? (
            <Highlighter
                highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
                searchWords={[this.state.searchText]}
                autoEscape
                textToHighlight={text.toString()}
            />
        ) : (
            text
        ),
  });
  handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    this.setState({
      searchText: selectedKeys[0],
      searchedColumn: dataIndex,
    });
  };
  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  initData = async () => {
    await this.setState({ dataLoading: true });
    await this.props.dispatch({ type: 'adminModel/getUserTable' });
    await this.setState({ dataLoading: false });
  };

  componentWillMount() {
    this.initData().then(() => null);
  }

  // render
  renderTable = () => {
    return (
        <div>
          <Table columns={this.columns}
                 dataSource={this.props.dataSource}
                 scroll={{ x: 'max-content' }}
                 loading={this.state.dataLoading}
                 bordered
          />
          <EditUserModal visible={this.state.modalVisible} hide={this.hideModal} userTable={this.state.userTable}/>
        </div>
    );
  };

  render() {
    return (
        <div>
          {this.renderTable()}
        </div>
    );
  }

}
